package cn.xenosp.server.common.handler;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.xenosp.server.common.Constant;
import cn.xenosp.server.common.SystemConfig;
import cn.xenosp.server.common.cache.Cache;
import cn.xenosp.server.common.tools.SecurityUtils;
import cn.xenosp.server.common.tools.SpringBeanUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 项目名： service-web
 * 包路径： cn.xenosp.server.common.handler
 * 作者：   TongHui
 * 创建时间: 2024-08-02 14:20
 * 描述: TODO
 * 版本: 1.0
 */
@Slf4j
@Data
public class ModelUpdateHandler implements HandlerInterceptor {

    Cache redisCache;




    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            StpUtil.checkActiveTimeout();
        } catch (NotLoginException e) {
            e.printStackTrace();
            log.warn("token已冻结，进行续签");
            StpUtil.updateLastActiveToNow();
        }
        // 在请求处理前执行的逻辑
        return true; // 返回 true 允许请求继续，返回 false 则终止请求
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
       if (modelAndView != null){
           // 在请求处理后、视图渲染前执行的逻辑
           SystemConfig systemConfig = null;
           if (redisCache.hasKey(Constant.SYSTEM_CONFIG)){
               systemConfig = (SystemConfig) redisCache.get(Constant.SYSTEM_CONFIG);
           }else {
               systemConfig = SpringBeanUtil.getBean(SystemConfig.class);
               redisCache.set(Constant.SYSTEM_CONFIG,systemConfig);
           }

           modelAndView.addObject(Constant.SYSTEM_CONFIG,systemConfig);
           if (StpUtil.isLogin()){
               String url = request.getHeader("page");
               String tokenValue = StpUtil.getTokenValue();
               Map<String,Object> map = (Map<String, Object>) redisCache.get(Constant.TOKEN+"_"+tokenValue);

               if (map != null){
                   modelAndView.addObject(Constant.MENUS,map.get("menu"));
               }
               if (url!=null){
                   List<String> permission = new ArrayList<>();
                   List<Map<String, Object>> responseList = (List<Map<String, Object>>) map.get("response");
                   String id = "";
                   for (Map<String, Object> resMap : responseList) {
                       String component = (String) resMap.get("component");
                       if (ObjectUtil.isNotEmpty(component) && url.endsWith(component)){
                           id = (String) resMap.get("menuId");
                           break;
                       }
                   }
                   for (Map<String, Object> resMap : responseList) {
                       String parentId = (String) resMap.get("parentId");
                       if (parentId.equals(id)&& resMap.get("type").equals("3")){
                           permission.add((String) resMap.get("permission"));
                       }
                   }
                   modelAndView.addObject(Constant.PERMISSION,permission);
               }
           }
       }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在整个请求完成后执行的逻辑
        SecurityUtils.removeLoginInfo();
    }
}
